<template>
  <component ref="_inner"
    :is="getComponent"
    v-bind="getWidgetProps"
    :disabled="getDisabledStatus()"
    :value="bindValue"
    @input="onValueInput"
    @change="onValueChange"
  />
</template>

<script>
import { findItemFromList, treeDataTranslate } from '@/utils';

export default {
  name: 'onlineCustomWidget',
  props: {
    value: {
      type: [String, Number, Boolean, Date, Object, Array]
    },
    widget: {
      type: Object,
      required: true
    }
  },
  inject: {
    form: {
      default: ''
    },
    parentWidget: {
      default: null
    }
  },
  data () {
    return {
      dictDataList: []
    }
  },
  methods: {
    reset () {
      if (this.getComponent === 'online-custom-chart') {
        this.$refs._inner.refresh();
      }
      this.onValueInput(undefined);
      this.onValueChange(undefined);
      this.$nextTick(() => {
        this.loadDropdownData();
      });
    },
    parseValue (val) {
      let bindColumnType = this.getColumnDataType;
      if (this.widget.widgetType === this.SysCustomWidgetType.Switch) {
        console.log(this.form().rules);
        // 根据绑定字段的类型，转换数据格式
        if (bindColumnType === 'Number') {
          return val ? 1 : false;
        } else if (bindColumnType === 'String') {
          return val ? 'true' : 'false';
        } else if (bindColumnType !== 'Boolean') {
          return false;
        } else {
          return val;
        }
      }
      if (this.widget.widgetType === this.SysCustomWidgetType.Cascader) {
        if (this.multiSelect) {
          return val.map(item => {
            return item[item.length - 1];
          }).filter(item => item != null);
        } else {
          return Array.isArray(val) ? val[val.length - 1] : val;
        }
      } else {
        return val;
      }
    },
    onValueInput (val) {
      let tempValue = this.parseValue(val);
      if (this.multiSelect) {
        tempValue = (Array.isArray(tempValue) && tempValue.length > 0) ? tempValue.join(',') : undefined;
      }
      console.log(tempValue);
      this.$emit('input', tempValue);
    },
    onValueChange (val, selectRow) {
      let tempVal = this.parseValue(val);
      let dictData = null;
      if (this.multiSelect) {
        dictData = val.map(item => {
          return findItemFromList(this.dictDataList, item, 'id');
        }).filter(item => item != null);
      } else {
        dictData = findItemFromList(this.dictDataList, val, 'id');
      }
      this.$emit('change', tempVal, {
        dictData: dictData,
        selectRow: selectRow
      });
    },
    loadDropdownData () {
      if (this.widget == null || !this.isDictWidget) {
        return;
      }
      this.dictDataList = [];
      let dictInfo = (this.widget.props.dictInfo || {}).dict;
      if (dictInfo && this.form().getDictDataList) {
        let dictCall;
        if (this.form().pageCode != null) {
          // 报表字典
          dictCall = this.form().getDictDataList(dictInfo, this.form().getDropdownParams(this.widget));
        } else {
          // 在线表单字典
          dictCall = this.form().getDictDataList(this, dictInfo, this.form().getDropdownParams(this.widget));
        }
        dictCall.then(res => {
          res.forEach(item => {
            item.id = item.id + '';
            if (item.parentId) item.parentId = item.parentId + '';
          });
          // 级联组件将列表转换成树
          if (this.widget.widgetType === this.SysCustomWidgetType.Cascader) {
            // res = treeDataTranslate(res, 'id', 'parentId');
          }
          if (this.widget.eventInfo && this.widget.eventInfo[this.OnlineFormEventType.DROPDOWN_CHANGE]) {
            res = this.widget.eventInfo[this.OnlineFormEventType.DROPDOWN_CHANGE](res);
          }
          this.dictDataList = res;
        }).catch(e => {
          console.log(e);
        });
      }
    },
    getDisabledStatus () {
      let formAuth = this.form().formAuth ? this.form().formAuth() : null;
      console.log(this.widget, formAuth);
      if (formAuth && formAuth.mobile) {
        let formWidgetAuth = formAuth.mobile[this.widget.variableName];
        if (formWidgetAuth && formWidgetAuth.disabled) return true;
      }
      if (this.widget.eventInfo && this.widget.eventInfo[this.OnlineFormEventType.DISABLE]) {
        return this.widget.eventInfo[this.OnlineFormEventType.DISABLE]();
      } else {
        return this.widget.props.disabled;
      }
    }
  },
  computed: {
    isDictWidget () {
      return [
        this.SysCustomWidgetType.Select,
        this.SysCustomWidgetType.CheckBox,
        this.SysCustomWidgetType.Radio,
        this.SysCustomWidgetType.Cascader,
        this.SysCustomWidgetType.Tree,
        this.SysCustomWidgetType.MobileCheckBoxFilter,
        this.SysCustomWidgetType.MobileRadioFilter
      ].indexOf(this.widget.widgetType) !== -1;
    },
    getColumnDataType () {
      if (this.widget == null || this.widget.column == null) return undefined;
      switch (this.widget.column.objectFieldType) {
        case 'String':
          return 'String';
        case 'Date':
          return 'Date';
        case 'Boolean':
          return 'Boolean';
        case 'Integer':
        case 'Long':
        case 'Float':
        case 'Double':
        case 'BigDecimal':
          return 'Number';
        default:
          return undefined;
      }
    },
    getVideoUrl () {
      let fileList = [];
      if (this.value != null) {
        let downloadParams = {
          ...this.buildFlowParam,
          datasourceId: (this.widget.datasource || {}).datasourceId,
          fieldName: this.widget.column.columnName,
          asImage: true,
          dataId: this.form().getPrimaryData(this.widget, this.rowData) || ''
        }
        if (this.widget.relation) downloadParams.relationId = this.widget.relation.relationId;
        let temp = JSON.parse(this.value);
        temp = Array.isArray(temp) ? temp.map(item => {
          return {
            ...item,
            downloadUri: this.getDownloadUrl
          }
        }) : [];
        fileList = this.parseUploadData(JSON.stringify(temp), downloadParams);
      }
      if (Array.isArray(fileList) && fileList.length > 0) {
        return fileList[0].url;
      }
      return this.value;
    },
    bindValue () {
      if (this.widget.widgetType === this.SysCustomWidgetType.Text) {
        return (this.value || this.widget.props.text || '') + '';
      }
      if (this.widget.widgetType === this.SysCustomWidgetType.Video) {
        return this.getVideoUrl();
      }
      if (this.multiSelect) {
        return (this.value || '').split(',').filter(item => item !== '');
      }
      let bindColumnType = this.getColumnDataType;
      let tempValue = this.value;
      if (this.widget.widgetType === this.SysCustomWidgetType.Switch) {
        if (bindColumnType === 'Number') {
          tempValue = Number.parseInt(tempValue);
          tempValue = !isNaN(tempValue) && tempValue !== 0 && tempValue != null && tempValue !== '';
        } else if (bindColumnType === 'String') {
          tempValue = tempValue === 'true';
        } else if (bindColumnType !== 'Boolean') {
          tempValue = false;
        }
        return tempValue;
      }
      if (this.value == null) return this.value;
      return this.isDictWidget ? (this.value + '') : this.value;
    },
    getComponent () {
      if (this.widget == null) return 'div';
      switch (this.widget.widgetType) {
        case this.SysCustomWidgetType.Label: return 'online-field-label';
        case this.SysCustomWidgetType.Input: return this.form().readOnly ? 'online-field-label' : 'van-field';
        case this.SysCustomWidgetType.Switch: return this.form().readOnly ? 'online-field-label' : 'van-field-switch';
        case this.SysCustomWidgetType.Radio: return this.form().readOnly ? 'online-field-label' : 'van-field-radio';
        case this.SysCustomWidgetType.CheckBox: return this.form().readOnly ? 'online-field-label' : 'van-field-checkbox';
        case this.SysCustomWidgetType.Select: return this.form().readOnly ? 'online-field-label' : 'van-field-select';
        case this.SysCustomWidgetType.Cascader: return this.form().readOnly ? 'online-field-label' : 'van-field-cascader';
        case this.SysCustomWidgetType.Calendar: return this.form().readOnly ? 'online-field-label' : 'van-field-calendar';
        case this.SysCustomWidgetType.Upload: return 'online-custom-upload';
        case this.SysCustomWidgetType.Stepper: return this.form().readOnly ? 'online-field-label' : 'van-field-stepper';
        case this.SysCustomWidgetType.Rate: return this.form().readOnly ? 'online-field-label' : 'van-field-rate';
        case this.SysCustomWidgetType.Signature: return 'van-field-signature';
        case this.SysCustomWidgetType.List: return 'van-online-list';
        case this.SysCustomWidgetType.CellGroup: return 'online-custom-group';
        case this.SysCustomWidgetType.Tabs: return 'online-custom-tabs';
        case this.SysCustomWidgetType.Image: return 'online-custom-image';
        case this.SysCustomWidgetType.Text: return 'custom-text';
        case this.SysCustomWidgetType.MobileRadioFilter: return 'van-select-filter';
        case this.SysCustomWidgetType.MobileCheckBoxFilter: return 'van-select-filter';
        case this.SysCustomWidgetType.MobileInputFilter: return 'van-search-filter';
        case this.SysCustomWidgetType.MobileSwitchFilter: return 'van-switch-filter';
        case this.SysCustomWidgetType.MobileDateRangeFilter: return 'van-datarange-filter';
        case this.SysCustomWidgetType.MobileNumberRangeFilter: return 'van-number-range-filter';
        case this.SysCustomWidgetType.UserSelect: return 'user-select';
        case this.SysCustomWidgetType.DeptSelect: return 'dept-select';
        case this.SysCustomWidgetType.DataSelect: return 'online-relation-select';
        case this.SysCustomWidgetType.Video: return 'van-field-video';
        case this.SysCustomWidgetType.MAP: return 'van-field-map';
        case this.SysCustomWidgetType.QRCODE: return 'van-field-qrcode';
        case this.SysCustomWidgetType.BARCODE: return 'van-field-barcode';
        case this.SysCustomWidgetType.LineChart:
        case this.SysCustomWidgetType.PieChart:
        case this.SysCustomWidgetType.BarChart:
        case this.SysCustomWidgetType.ScatterChart:
        case this.SysCustomWidgetType.PivotTable:
        case this.SysCustomWidgetType.DataViewTable:
        case this.SysCustomWidgetType.Carousel:
        case this.SysCustomWidgetType.RichText:
        case this.SysCustomWidgetType.GaugeChart:
        case this.SysCustomWidgetType.FunnelChart:
        case this.SysCustomWidgetType.RadarChart:
        case this.SysCustomWidgetType.ProgressBar:
        case this.SysCustomWidgetType.ProgressCircle:
        case this.SysCustomWidgetType.DataCard:
        case this.SysCustomWidgetType.DataProgressCard:
        case this.SysCustomWidgetType.CommonList:
          return 'online-custom-chart';
        default: return 'div';
      }
    },
    getListWidgetDataList () {
      if (this.widget.widgetType === this.SysCustomWidgetType.List) {
        if (this.widget.table && this.widget.table.relation) {
          return this.form().formData[this.widget.table.relation.variableName];
        }
      }

      return undefined;
    },
    getWidgetProps () {
      let props = {
        ...this.widget.props || {}
      };
      return {
        ...props,
        clearable: true,
        filterable: true,
        readonly: this.form().readOnly ? this.form().readOnly : props.readonly,
        multiple: this.multiSelect,
        dataList: this.widget.widgetType === this.SysCustomWidgetType.Cascader ? treeDataTranslate(this.dictDataList.map(item => {
          return {
            ...item,
            children: undefined
          }
        }), 'id', 'parentId') : this.dictDataList,
        label: this.widget.showName,
        widget: this.widget,
        props: this.widget.widgetType === this.SysCustomWidgetType.DataSelect ? {
          datasourceId: (this.widget.props.relativeTable || {}).datasourceId,
          relationId: (this.widget.props.relativeTable || {}).relationId,
          relativeFormId: (this.widget.props.relativeTable || {}).relativeFormId,
          variableName: (this.widget.props.relativeTable || {}).variableName,
          relationTableName: (this.widget.props.relativeTable || {}).relativeTableName,
          relationColumnName: (this.widget.props.relativeTable || {}).relativeColumn,
          displayField: (this.widget.props.relativeTable || {}).displayField
        } : undefined,
        rules: (this.form().rules || {})[this.widget.propString],
        isHtml: this.widget.column && this.widget.column.isRichText && this.widget.widgetType === this.SysCustomWidgetType.Text
      };
    },
    multiSelect () {
      if (
        [
          this.SysCustomWidgetType.Select,
          this.SysCustomWidgetType.CheckBox,
          this.SysCustomWidgetType.Cascader,
          this.SysCustomWidgetType.Tree,
          this.SysCustomWidgetType.MobileCheckBoxFilter,
          this.SysCustomWidgetType.MobileRadioFilter
        ].indexOf(this.widget.widgetType) === -1
      ) {
        return false;
      }
      if (this.widget.widgetType === this.SysCustomWidgetType.CheckBox) return true;
      if (this.form().formType === this.SysOnlineFormType.QUERY || this.form().formType === this.SysOnlineFormType.ADVANCE_QUERY) {
        console.log(this.widget.column);
        return this.widget.column && this.widget.column.filterType === this.SysOnlineColumnFilterType.MULTI_SELECT_FILTER;
      } else if (this.form().formType === this.SysOnlineFormType.REPORT) {
        return this.SysCustomWidgetType.CheckBox === this.widget.widgetType;
      } else {
        return this.widget.column && this.widget.column.fieldKind === this.SysOnlineFieldKind.MULTI_SELECT;
      }
    }
  },
  mounted () {
    this.widget.widgetImpl = this;
    this.$nextTick(() => {
      if (this.widget) this.loadDropdownData();
    });
  }
}
</script>

<style>
</style>
